function X_OU = OU(dt,t, g, D)
% Simulating a one-dimensional Ornstein-Uhlenbeck process in MATLAB 
% Given a vector 't' of times, linearly spaced at intervals 'dt',
%with 'g' and 'D' your damping parameter and diffusion coefficient respectively, 
%then the following lines of code will simulate the Ornstein-Uhlenbeck process:
%dX_free = sqrt(2*D)  * dW
%dX_filt = - g (x_filt - x_free) * dt
%dX_ou = - g x_ou * dt + sqrt(2*D) * dW

X_free = cumsum(sqrt(2*D*dt)*randn(size(t)));
X_filt = filter([0 g*dt], [1 -1+g*dt] , X_free);
X_OU = X_free-X_filt;